//
//  OrderForm_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/31.
//
//


/*
 owner:cy
 update:2017年03月31日11:42:46
 info: 进货单
 */
import RxSwift
import UtilCore
import RickonCore
import EmptyDataView
import BrandonCore

class OrderForm_Vc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var orderForm_Tv: UITableView!
    
    @IBOutlet weak var allIsCheck_Btn: UIButton!
    
    @IBOutlet weak var allTotalShprice_Lb: UILabel!
    
    @IBOutlet weak var allPostage_Lb: UILabel!
    ///当数据为空的时候隐藏底部 默认为50
    @IBOutlet weak var bottom_Height: NSLayoutConstraint!
    @IBOutlet weak var bottom_V: UIView!
    @IBOutlet weak var edit_Btn: UIButton!
    @IBOutlet weak var submit_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    var manageVm:OrderForm_Vm?
    
    var orderFormModel :OrderFormModel?{
        didSet{
            self.updateOrderFormTvData()
        }
    }
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        if let navgationVc = self.navigationController , navgationVc.viewControllers.count > 1 {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "iconfont-back"), style: .plain, target: self, action: #selector(backToView))
        }
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        self.customLeftBarButtonItem()
        self.orderForm_Tv.dzn_tv_emptyDelegate = self
        self.orderForm_Tv.dzn_tv_emptyDataSource = self
        self.orderForm_Tv.backgroundView = nil
        self.orderForm_Tv.backgroundColor = UIColor.clear
        self.submit_Btn.setTitle("结算(\(self.orderFormModel?.buyNum ?? 0))", for: .normal)
        self.allTotalShprice_Lb.text = "合计:\(self.orderFormModel?.buyMoney.getFormatStr() ?? "0.00")元"
        ///隐藏滑动条
        self.orderForm_Tv.showsVerticalScrollIndicator = false
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.submit_Btn.backgroundColor = UIColor.clear
        self.submit_Btn.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.arya.orderForm.addCartisabled_Btn)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = OrderForm_Vm(refreshTriger: rx.sentMessage(#selector(OrderForm_Vc.viewWillAppear)).map { _ in () }.filter{ _ -> Bool in
            if case  .audited = AppData.appState{
                return true
            }else{
                AuditInfoView.showByView(supView: self.view)
                return false
                
            }
        })
        self.manageVm?.productItem
            .subscribe(onNext: {[unowned self] (list) in
                /// 需要显示空列表
                self.showEmptyView = true
                self.orderFormModel = list
            })
            .disposed(by: disposeBag)
        self.allIsCheck_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if let model = self.orderFormModel{
                    model.hasSelected = !model.hasSelected
                }
                self.updateOrderFormTvData()
            })
            .disposed(by: disposeBag)
        self.submit_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if self.edit_Btn.isSelected == false {
                    if let order = self.orderFormModel{
                        _ = "cofirmorder".openURL(["osCarts":self.getSubmitParam(effective: order.effective) as String,"iscart":"1"])
                    }
                }else{
                    /// 删除事件
                    if let order = self.orderFormModel{
                        self.manageVm?.delSubject.onNext(self.getdDelParam(effective: order.effective))
                    }
                }
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .loading
            .asObservable()
            .bindTo(self.view.rx_loading)
            .disposed(by: disposeBag)
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        
        self.edit_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.edit_Btn.isSelected = !self.edit_Btn.isSelected
                self.updateOrderFormTvData()
            })
            .disposed(by: disposeBag)
        self.manageVm?.delSuccess
            .subscribe(onNext: { (_) in
                /// 获取进货单数量
                _ = "orderformbadge".openURL()
            })
            .addDisposableTo(disposeBag)
    }
}
extension OrderForm_Vc{
    /// 获取需要删除商品的购物车id参数
    func getdDelParam(effective:[OrderProductModel]) -> String {
        var sparmArr:[String] = []
        for order in effective{
            for item in order.array {
                for subItem in item.array {
                    /// 只选择选中的
                    if subItem.hasSelected {
                        sparmArr.append("\(subItem.cartid)")
                    }
                }
            }
        }
        return sparmArr.joined(separator: ",")
    }
    /// 获取需要清空的失效商品的购物车id参数
    func getdclearLoseefficacyParam(loseefficacy:[OrderProductModel]) -> String {
        var sparmArr:[String] = []
        for order in loseefficacy{
            for subItem in order.array {
                sparmArr.append("\(subItem.cartid)")
            }
            
        }
        return sparmArr.joined(separator: ",")
    }
    func getSubmitParam(effective:[OrderProductModel]) -> String {
        var sparmArr:[[String:String]] = []
        guard let user = AppData.loginedUser else {
            return ""
        }
        for order in effective{
            for item in order.array {
                for subItem in item.array {
                    if subItem.cartnumber > 0 {
                        /// 只选择选中的
                        var subRelItem :[String:String] = [:]
                        subRelItem["brid"] = "\(subItem.brid)"
                        subRelItem["ischeck"] = "\(subItem.ischeck)"
                        subRelItem["pdid"] = "\(subItem.pdid)"
                        subRelItem["spid"] = "\(user.glShop.spid)"
                        subRelItem["skuid"] = "\(subItem.skuid)"
                        /// 购物车的需要添加 cartid
                        subRelItem["cartid"] = "\(subItem.cartid)"
                        subRelItem["cartnumber"] = "\(subItem.cartnumber)"
                        sparmArr.append(subRelItem)
                    }
                }
            }
        }
        return JSONHelper.parseToJson(sparmArr as AnyObject) as String
    }
    ///当数据为空时隐藏底部view
    func updateBottomView(isHide:Bool) {
        self.bottom_V.isHidden = isHide
        self.edit_Btn.isHidden = isHide
        if isHide {
            self.bottom_Height.constant = 0
            
        }else{
            self.bottom_Height.constant = 50
        }
    }
    func updateOrderFormTvData() -> Void {
        self.allIsCheck_Btn.isSelected = self.orderFormModel?.hasSelected ?? false
        if self.edit_Btn.isSelected {
            /// 显示删除状态
            self.allTotalShprice_Lb.isHidden = true
            self.allPostage_Lb.isHidden = true
            self.submit_Btn.setTitle("删除", for: .normal)
            self.submit_Btn.setTitleColor(UIColor.white, for: .normal)
            self.submit_Btn.backgroundColor = Theme.arya.orderForm.delete_btn
        }else{
            self.allTotalShprice_Lb.isHidden = false
            self.allPostage_Lb.isHidden = false
            self.submit_Btn.setTitle("结算(\(self.orderFormModel?.buyNum ?? 0))", for: .normal)
            self.submit_Btn.setTitleColor(UIColor.white, for: .normal)
            self.submit_Btn.backgroundColor = Theme.btn.normal
        }
        self.allTotalShprice_Lb.text = "合计:\(self.orderFormModel?.buyMoney.getFormatStr() ?? "0.00")元"
        if let order = self.orderFormModel {
            /// 如果进货单数据为空的时候需要 更新为 结算状态
            if order.effective.count == 0 {
                /// 标志位不可以点击状态
                self.submit_Btn.isEnabled = false
            }else{
                /// 这块判断submit按钮的是否可以点击状态 需要多一层考虑 ，如果当前显示的是删除，需要判断所有子节点中只要包含有选中的就可以删除 否则不行， 如果显示的是结算 则需要判断 buynum 是否为0 如果为0 则不能点击 否则可以点击
                if self.edit_Btn.isSelected == false {
                    /// 按钮显示: 结算
                    if order.buyNum == 0 {
                        self.submit_Btn.isEnabled = false
                    }else{
                        self.submit_Btn.isEnabled = true
                    }
                }else{
                    /// 按钮显示: 删除
                    ///需要判断 子节点中是否包含有选中的元素 如果有则可以点击否则不能点击
                    if order.isHsaSelected {
                        self.submit_Btn.isEnabled = true
                    }else{
                        self.submit_Btn.isEnabled = false
                    }
                    
                }
            }
            self.orderForm_Tv.reloadData()
        }else{
            self.submit_Btn.isEnabled = false
        }
        
    }
}
// MARK: UITableViewDelegate
extension OrderForm_Vc :UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        var count:Int = 0
        if let model = self.orderFormModel {
            if model.loseefficacy.count > 0 {
                count = model.effective.count + 1 + model.loseefficacy.count
            }else{
                count = model.effective.count
            }
        }else{
            count = 0
        }
        updateBottomView(isHide: count == 0)
        return count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if let model = self.orderFormModel {
            /// 首先先判断是否包含失效商品
            if model.loseefficacy.count > 0 {
                /// 有效的商品
                if model.effective.count > 0 {
                    if section < model.effective.count {
                        return model.effective[section].array.count
                    }else if section == model.effective.count{
                        /// 显示失效  清除 cell
                        return 1
                    }else{
                        return model.loseefficacy[section - model.effective.count - 1].array.count
                    }
                }else{
                    /// 这块是只有失效的商品
                    if section == 0 {
                        return 1
                    }else{
                        return model.loseefficacy[section - 1].array.count
                    }
                }
            }else{
                return model.effective[section].array.count
            }
        }else{
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            /// 有效的商品
            if effectiveCount > 0 {
                if indexPath.section < effectiveCount {
                    /// 绘制有效商品
                    let item = model.effective[indexPath.section].array[indexPath.row]
                    let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_Normal_TCell", for: indexPath) as! OrderForm_Normal_TCell
                    cell.item = item
                    cell.updateBtnState_Closure = {[unowned self] _ in
                        self.updateOrderFormTvData()
                    }
                    cell.updateCartNum_Closure = {[unowned self] param in
                        self.updateOrderFormTvData()
                        self.manageVm?.updateCartSubject.onNext(param)
                    }
                    return cell
                }else if indexPath.section == effectiveCount{
                    /// 显示失效  清除 cell
                    let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_ClearEfficacy_Hv", for: indexPath) as! OrderForm_ClearEfficacy_Hv
                    cell.didClear_Closure = {[unowned self] _ in
                        self.manageVm?.delSubject.onNext(self.getdclearLoseefficacyParam(loseefficacy: model.loseefficacy))
                    }
                    return cell
                }else{
                    /// 绘制失效商品的
                    let item = model.loseefficacy[indexPath.section - 1 - model.effective.count].array[indexPath.row]
                    let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_Efficacy_TCell", for: indexPath) as! OrderForm_Efficacy_TCell
                    cell.item = item
                    return cell
                }
            }else{
                /// 这块是只有失效的商品
                if indexPath.section == 0 {
                    /// 显示失效  清除 cell
                    let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_ClearEfficacy_Hv", for: indexPath) as! OrderForm_ClearEfficacy_Hv
                    cell.didClear_Closure = {[unowned self] _ in
                        self.manageVm?.delSubject.onNext(self.getdclearLoseefficacyParam(loseefficacy: model.loseefficacy))
                    }
                    return cell
                }else{
                    /// 绘制失效商品的
                    let item = model.loseefficacy[indexPath.section - 1].array[indexPath.row]
                    let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_Efficacy_TCell", for: indexPath) as! OrderForm_Efficacy_TCell
                    cell.item = item
                    return cell
                }
            }
        }else{
            /// 只有 有效商品
            /// 绘制有效商品
            let item = model.effective[indexPath.section].array[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderForm_Normal_TCell", for: indexPath) as! OrderForm_Normal_TCell
            cell.item = item
            cell.updateBtnState_Closure = {[unowned self] _ in
                self.updateOrderFormTvData()
            }
            cell.updateCartNum_Closure = {[unowned self] param in
                self.updateOrderFormTvData()
                self.manageVm?.updateCartSubject.onNext(param)
            }
            return cell
        }
    }

    
}
// MARK: UITableViewDelegate
extension OrderForm_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true)
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            /// 有效的商品
            if effectiveCount > 0 {
                if indexPath.section < effectiveCount {
                    let item  = model.effective[indexPath.section].array[indexPath.row]
                    _ = "productdetail".openURL(["pdid":"\(item.pdid)"])
                }
            }
        }else{
            /// 只有 有效商品
            /// 绘制有效商品
            let item  = self.orderFormModel!.effective[indexPath.section].array[indexPath.row]
            _ = "productdetail".openURL(["pdid":"\(item.pdid)"])
            
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            /// 有效的商品
            if effectiveCount > 0 {
                if indexPath.section < effectiveCount {
                    let item  = model.effective[indexPath.section].array[indexPath.row]
                    ///  1表示分割线
                    return CGFloat(85 * item.array.count) + 1 + 86
                }else if indexPath.section == effectiveCount{
                    /// 显示失效  清除 cell
                    return 44
                }else{
                    return 85
                }
            }else{
                /// 这块是只有失效的商品
                if indexPath.section == 0 {
                    return 44
                }else{
                    return 85
                }
            }
        }
        let item  = model.effective[indexPath.section].array[indexPath.row]
        ///  1表示分割线
        return CGFloat(85 * item.array.count) + 1 + 86
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            if section == effectiveCount {
                return 0
            }else{
                return 40
            }
        }
        return 40
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            if section == effectiveCount {
                return 0
            }else{
                return 40
            }
        }
        return 40
    }
    ///自定义view
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            /// 有效的商品
            if effectiveCount > 0 {
                if section < effectiveCount {
                    let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Normal_Hv") as! OrderForm_Normal_Hv
                    let item  = self.orderFormModel!.effective[section]
                    cell.item = item
                    cell.updateBtnState_Closure = {[unowned self] _ in
                        self.updateOrderFormTvData()
                    }
                    return cell
                }else if section == effectiveCount{
                    /// 显示失效  清除 cell
                    return nil
                }else{
                    /// 绘制 失效的 公司 header
                    let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Efficacy_Hv") as! OrderForm_Efficacy_Hv
                    let item  = model.effective[section - 1 - model.loseefficacy.count]
                    cell.item = item
                    return cell
                }
            }else{
                /// 这块是只有失效的商品
                if section == 0 {
                    /// 显示失效  清除 cell
                    return nil
                }else{
                    /// 绘制 失效的 公司 header
                    let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Efficacy_Hv") as! OrderForm_Efficacy_Hv
                    let item  = model.loseefficacy[section - 1]
                    cell.item = item
                    return cell
                }
                
            }
        }else{
            /// 只有 有效商品
            /// 绘制有效商品
            let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Normal_Hv") as! OrderForm_Normal_Hv
            let item  = self.orderFormModel!.effective[section]
            cell.item = item
            cell.updateBtnState_Closure = {[unowned self] _ in
                self.updateOrderFormTvData()
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let model = self.orderFormModel!
        /// 失效的数组大小
        let loseeCount = model.loseefficacy.count
        /// 有效数组大小
        let effectiveCount = model.effective.count
        /// 首先先判断是否包含失效商品
        if loseeCount > 0 {
            /// 有效的商品
            if effectiveCount > 0 {
                if section < effectiveCount {
                    let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Footer_Hv") as! OrderForm_Footer_Hv
                    let item  = self.orderFormModel!.effective[section]
                    cell.item = item
                    return cell
                }else if section == effectiveCount{
                    /// 显示失效  清除 cell
                    return nil
                }else{
                    return nil
                }
            }else{
                /// 这块是只有失效的商品
                return nil
            }
        }
        let cell = self.orderForm_Tv.dequeueReusableCell(withIdentifier: "OrderForm_Footer_Hv") as! OrderForm_Footer_Hv
        let item  = self.orderFormModel!.effective[section]
        cell.item = item
        return cell
    }
    
}
//extension OrderForm_Vc :UIScrollViewDelegate{
//    func scrollViewDidScroll(_ scrollView: UIScrollView){
//        let sectionHeaderHeight:CGFloat = 50
//        if scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0 {
//            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//        } else if scrollView.contentOffset.y>=sectionHeaderHeight {
//            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//        }
//    }
//}
///EmptyDelegate 空数据代理
extension OrderForm_Vc{
    override func didTap(emptyView scrollView: UIScrollView, button: UIButton){
        
    }
}
/// 空数据数据代理
extension OrderForm_Vc :EmptyDataSource{
    
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString?{
        return Theme.getEmptyDesc("进货单还没有商品~")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage?{
        return UIImage(named: "shopcart_empty", in: AryaCore.bundle, compatibleWith: nil)
    }
    
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}

